package com.timemanage.activity.ui.dashboard

import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.github.aachartmodel.aainfographics.aachartcreator.*
import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAStyle
import com.github.aachartmodel.aainfographics.aaoptionsmodel.AATooltip
import com.loper7.date_time_picker.DateTimePicker
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.timemanage.R
import com.timemanage.activity.ui.mine.MineFragment
import com.timemanage.dao.AppDatabase
import com.timemanage.dao.UserDao

import com.timemanage.entity.User
import com.timemanage.entity.Work
import com.timemanage.utils.AlarmService
import com.timemanage.utils.MyApplication
import com.timemanage.utils.postUI
import kotlinx.android.synthetic.main.fragment_dashboard.*
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.collections.HashMap
import kotlin.concurrent.thread
import kotlin.math.log
import kotlin.math.max
import kotlin.math.min
import android.content.Context.BIND_AUTO_CREATE




class DashboardFragment : Fragment() {



    val daymill:Long =86400000//每天毫秒数

    var database = AppDatabase.getDatabase(MyApplication.context)
    var userdao: UserDao = database.userDao();
    var workDao = database.WorkDao()
//    var user1: User = User("mhz","mhz123")
    var work: List<Work>? = null
    var empty = emptyList<Collection<Any>>()

    var aaelement= AASeriesElement().name("Time Spent(min)")
    var bbelement=AASeriesElement().name("最近30天时间花费")
    lateinit var aaChartView:AAChartView
    lateinit var bbChartView:AAChartView
    lateinit var ccChartView:AAChartView
    lateinit var buttomStart:Button
    lateinit var buttomEnd:Button



    val aaChartModel: AAChartModel = AAChartModel()
        .chartType(AAChartType.Pie)
        .title("用户各项活动使用时长占比")
        .subtitle("大类")
        .backgroundColor("#87CEEB")
         .dataLabelsEnabled(true)
        .gradientColorEnable(true)


    var timeMap = HashMap<String, Long>(mapOf("startTime" to 0,"endTime" to System.currentTimeMillis()))

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_dashboard,container,false)
        aaChartView = view.findViewById(R.id.aa_chart_viewpie)
        bbChartView=view.findViewById(R.id.aa_chart_view1)
        ccChartView=view.findViewById(R.id.aa_chart_view2)
        buttomStart= view.findViewById(R.id.timestart)
        buttomEnd=view.findViewById(R.id.timeend)


        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        //数据库初始化（测试用）
//        thread {
//
//            initSQl()
//
//        }

        //查询表，统计各大类活动花费时间(饼图）


        this.activity.postUI{
            work = workDao.selectMainType()
            val user: User = userdao.selectAcUser()
            for (w in work!!) {

                var works =
                    workDao.selectByTime(user.userId, w.workId, 100, System.currentTimeMillis())

                var time: Long = 0
//                for (ws in works) {
//                    time += (ws.endTime!! - ws.startTime!!)
//
//                }
                time=dfs(user.userId,w.workId,System.currentTimeMillis())
                empty = empty.plusElement(
                    arrayListOf(
                        w.title,
                        TimeUnit.MILLISECONDS.toMinutes(time)
                    )
                ) as List<Collection<Any>>
            }

            //绘制图形
            aaelement.data(empty.toTypedArray())
            aaChartModel.series(arrayOf(aaelement))
            aaChartView.aa_drawChartWithChartModel(aaChartModel)

            //折线图
            var timeArray = emptyArray<Any>()

            var time: Long =
                System.currentTimeMillis() - 29 * daymill - System.currentTimeMillis() % daymill

            var ptime: Long = time -  daymill- 28800000//30天前的整点时间

            var works = workDao.selectDayTime(user.userId, ptime)
            for (i in 1..30) {

                var times: Long = 0
                for (ws in works) {
                    if(ws.startTime!! >=ptime && ws.startTime!!<=ptime+daymill)//任务可能跨天，需要截取
                    {
                        times += (min(ptime + daymill, ws.endTime!!) - max(ws.startTime!!, ptime))
                    }

                }
                timeArray = timeArray.plusElement(TimeUnit.MILLISECONDS.toMinutes(times))
                ptime += daymill
            }
            bbelement.data(timeArray)


            var bbChartModel: AAChartModel = AAChartModel()
                //选择图表类型
                .chartType(AAChartType.Line)
                .colorsTheme(arrayOf("#465DBC"))
                //title标题
                .title("近30天有效利用时间变化图")
                .colorsTheme(arrayOf("#febc0f", "#FF14d4", "#0bf8f5", "#F33c52", "#1904dd"))
                .titleStyle(
                    AAStyle()
                        .color("#0F0F0F")
                        .fontSize(15f)
                )
                //坐标轴字体颜色
                .axesTextColor("#0F0F0F")
                //背景颜色
                .zoomType(AAChartZoomType.XY)
                .backgroundColor("#87CEEB")
                //数据是否显示
                .dataLabelsEnabled(true)
                //x轴是否显示数据
                .xAxisLabelsEnabled(true)
                //x轴显示的数据间隔
                .xAxisTickInterval(3)
                //y轴是否显示数据
                .yAxisLabelsEnabled(true)
                //y轴标题
                .yAxisTitle("时间(min)")
                .yAxisAllowDecimals(true) //y轴数据
                .series(arrayOf(bbelement))



            bbChartView.aa_drawChartWithChartModel(bbChartModel)

            //测试
            var ccChartModel: AAChartModel = AAChartModel()
                .chartType(AAChartType.Column)
                .backgroundColor("#87CEEB")
                .title("用户时间花费")
                .colorsTheme(arrayOf("#febc0f", "#FF14d4", "#0bf8f5", "#F33c52", "#1904dd"))
                .series(
                    arrayOf(
                        aaelement.colorByPoint(true)
                    )
                )



            ccChartView.aa_drawChartWithChartModel(ccChartModel)

        }


        //时间


        buttomStart.setOnClickListener {
            this.activity?.let {
                CardDatePickerDialog.builder(it)
                    .setTitle("请选择时间")
                    .setOnChoose("选择"){
                            millisecond ->
                        timeMap["startTime"]=millisecond
                     //   Custom(timeMap["startTime"]!!,timeMap["endTime"]!!)
                    }.setOnCancel("关闭") {}
                    .build().show()
            }
        }

        buttomEnd.setOnClickListener {

            this.activity?.let {

                val that=it
                CardDatePickerDialog.builder(it)
                    .setTitle("请选择时间")
                    .setOnChoose("选择"){
                        millisecond ->
                            timeMap["endTime"]=millisecond
                            Custom(timeMap["startTime"]!!,timeMap["endTime"]!!)
                    }.setOnCancel("关闭") {}
                    .build().show()
            }

        }

   }


        fun Custom(stTime: Long, enTime: Long) {
            var empty1 = emptyList<Collection<Any>>()
            var aaelement1 = AASeriesElement().name("Time Spent(min)")

            var work = workDao.selectMainType()

            val user: User = userdao.selectAcUser()
            for (w in work!!) {

                var works = workDao.selectByTime(user.userId, w.workId, stTime, enTime)

                var time: Long = 0
                for (ws in works) {
                    time += (ws.endTime!! - ws.startTime!!)

                }
                empty1 = empty1.plusElement(
                    arrayListOf(
                        w.title,
                        TimeUnit.MILLISECONDS.toMinutes(time)
                    )
                ) as List<Collection<Any>>
            }


            aaelement1.data(empty1.toTypedArray())
            aaChartView.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(arrayOf(aaelement1))
            ccChartView.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(
                arrayOf(
                    aaelement1.colorByPoint(
                        true
                    )
                )
            )


        }

    fun dfs(userid:Int,workid:Int,nowTime:Long):Long{

        var totaltime:Long=0;

        var works = workDao.selectByTime(userid, workid, 100, nowTime)
        var zhonglei=workDao.selectSonType(userid,workid)

        if(works==null&&zhonglei==null)
        {
            return totaltime
        }
        var time: Long = 0
        //具体任务不空
        if(works!=null)
            for (ws in works) {
                time += (ws.endTime!! - ws.startTime!!)
                Log.d("dfs",ws.title.toString())
            }

        totaltime=time

        if(zhonglei!=null)
            for( z in zhonglei) {
                Log.d("zl",z.title.toString())
                totaltime+=dfs(userid,z.workId,nowTime)
            }

        return totaltime

    }
}

